package com.cgbl.cg.vm.login

import android.app.Application
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.blankj.utilcode.util.StringUtils
import com.cgbl.cg.R
import com.cgbl.cg.im.ImManager
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.configs.PrefsManager
import com.robot.base.model.LoginBean
import com.robot.base.model.UserInfoBean
import com.robot.base.util.StringUtil
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import com.robot.base.utils.JobUtil
import com.umeng.socialize.bean.SHARE_MEDIA
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.http.BaseResponse

class BindPhoneViewModel(application: Application) : GLBaseViewModel(application) {
    var name = ""
    var type = ""
    var imgUrl = ""
    var openId = ""
    val codeText = ObservableField(StringUtils.getString(R.string.app_en_tips_19))
    val codeEnable = ObservableField(true)
    val promptSelect = ObservableField(false)

    val phone = ObservableField<String>()
    val code = ObservableField<String>()
    val password = ObservableField<String>()

    val promptClick = BindingCommand<Any>(BindingAction {
        promptSelect.set(!promptSelect.get()!!)
    })

    val sendCodeCommand = BindingCommand<Any>(BindingAction {
        if (!StringUtil.checkPhone(phone.get())) {
            ToastUtils.showShort("请输入正确的手机号码")
            return@BindingAction
        }
        setViewData()
    })


    val toBindAccountCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(AppConstants.Router.Login.A_LOGIN_BIND_ACCOUNT)
    })

    val confirmCommand = BindingCommand<Any>(BindingAction {
        if (checkPrompt()) return@BindingAction
        doLogin()
    })


    private fun checkPrompt(): Boolean {
        if (promptSelect.get() == false) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_4))
        }
        return promptSelect.get() == false
    }

    private fun setViewData() {
        codeEnable.set(false)
        val job = JobUtil.countDownCoroutines(60, {
            codeText.set("${it}${StringUtils.getString(R.string.app_en_tips_23)}")
        }, {
            codeText.set(StringUtils.getString(R.string.app_en_tips_20))
            codeEnable.set(true)
        })
        job.start()
        sendSmsVerifyCode()
    }

    private fun sendSmsVerifyCode() {
        UserServiceFactory.sendSmsVerifyCode(
            mapOf(
                "mobile" to phone.get(), "scene" to "1"
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                ToastUtils.showShort("发送成功")
            }
        })
    }

    private fun doLogin() {
        val loginParams = mapOf(
            "avatar" to imgUrl,
            "mobile" to phone.get(),
            "nickname" to name,
            "openId" to openId,
            "smsCode" to code.get(),
            "password" to password.get(),
            "type" to type
        )
        showLoadingDialog()
        UserServiceFactory.weChatBindPhoneLogin(loginParams).flatMap {
            PrefsManager.saveUserLoginInfo(it.data)
            PrefsManager.loginSuccess()
            return@flatMap UserServiceFactory.userInfo()
        }.subscribe(object : AbstractViewModelSubscriber<BaseResponse<UserInfoBean>>(this) {
            override fun onNext(t: BaseResponse<UserInfoBean>) {
                dismissLoadingDialog()
                PrefsManager.saveUserInfo(t.data)
                val account = PrefsManager.getUserInfo().accid;
                val imToken = PrefsManager.getUserInfo().imToken
                ImManager.startLogin(account, imToken, object : ImManager.LoginListener {
                    override fun loginSuccess() {
                        ARouterUtil.goToActivity(AppConstants.Router.Main.A_MAIN)
                        finish()
                    }

                    override fun loginFailed() {
                        ToastUtils.showShort("登录IM系统失败!")
                    }
                })
            }
        })
    }
}